//
//  CommentsPopView.m
//  Douyin
//
//  Created by Qiao Shi on 2018/7/30.
//  Copyright © 2018年 Qiao Shi. All rights reserved.
//

#import "CommentsPopView.h"
#import "Masonry.h"
#import "NSNotification+Extension.h"
#import "MenuPopView.h"
#import "MHComment.h"
#import "NSString+Extension.h"
#import "NSDateFormatter+Extension.h"
#import "NSDate+Extension.h"
#import "MHAwemeModel.h"
#import "UIImage+Extension.h"
#import "NSMutableAttributedString+MHMoment.h"
//#import "<#header#>"
//#import "NetworkHelper.h"

#define COMMENT_CELL @"CommentCell"
#define COMMENT_HEADER @"CommentHeader"
#define COMMENT_FOOTER @"CommentFooter"

@interface CommentsPopView () <UITableViewDelegate,UITableViewDataSource, UIGestureRecognizerDelegate,UIScrollViewDelegate, CommentTextViewDelegate>

@property (nonatomic, assign) MHAwemeModel                         *aweme;
//@property (nonatomic, strong) Visitor                          *vistor;

@property (nonatomic, assign) NSInteger                        pageIndex;
@property (nonatomic, assign) NSInteger                        pageSize;

@property (nonatomic, strong) UIView                           *container;
@property (nonatomic, strong) UITableView                      *tableView;
@property (nonatomic, strong) NSMutableArray<MHComment *>        *data;
@property (nonatomic, strong) CommentTextView                  *textView;
@property (nonatomic, strong) LoadMoreControl                     *loadMore;


@end

@implementation CommentsPopView
- (instancetype)initWithAwemeId:(MHAwemeModel *)aweme {
    self = [super init];
    if (self) {
        self.frame = SCREEN_FRAME;
        UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleGuesture:)];
        tapGestureRecognizer.delegate = self;
        [self addGestureRecognizer:tapGestureRecognizer];
        
        _aweme = aweme;
        //        _vistor = readVisitor();
        
        _pageIndex = 1;
        _pageSize = 20;
        
        _data = [NSMutableArray array];
        
        _container = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT*3/4)];
        _container.backgroundColor = MHWhiteTextColor;
        [self addSubview:_container];
        
        
        UIBezierPath* rounded = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT*3/4) byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(10.0f, 10.0f)];
        CAShapeLayer* shape = [[CAShapeLayer alloc] init];
        [shape setPath:rounded.CGPath];
        _container.layer.mask = shape;
        
        UIBlurEffect *blurEffect =[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
        UIVisualEffectView *visualEffectView = [[UIVisualEffectView alloc]initWithEffect:blurEffect];
        visualEffectView.frame = self.bounds;
        visualEffectView.alpha = 1.0f;
        [_container addSubview:visualEffectView];
        
        
        _label = [[UILabel alloc] init];
        _label.textColor = MHTextColor000;
        _label.text = @"评论";
        _label.font = MHRegularFont_14;
        _label.textAlignment = NSTextAlignmentLeft;
        [_container addSubview:_label];
        
        _close = [[UIImageView alloc] init];
        _close.image = [UIImage imageNamed:@"icon_closetopic"];
        _close.contentMode = UIViewContentModeCenter;
        [_close addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleGuesture:)]];
        [_container addSubview:_close];
        [_label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.right.equalTo(self.container);
            make.left.mas_equalTo(15);
            make.height.mas_equalTo(35);
        }];
        [_close mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.label);
            make.right.equalTo(self.label).inset(10);
            make.width.height.mas_equalTo(30);
        }];
        
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 35, SCREEN_WIDTH, SCREEN_HEIGHT*3/4 - 35 - 50) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = ColorClear;
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.tableView.bounds.size.width, 0.01f)];
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, 50, 0);
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:CommentListCell.class forCellReuseIdentifier:COMMENT_CELL];
        
        _loadMore = [[LoadMoreControl alloc] initWithFrame:CGRectMake(0, 100, SCREEN_WIDTH, 50) surplusCount:10];
        [_loadMore startLoading];
        __weak __typeof(self) wself = self;
        [_loadMore setOnLoad:^{
            [wself loadData:wself.pageIndex pageSize:wself.pageSize];
        }];
        [_tableView addSubview:_loadMore];
        
        [_container addSubview:_tableView];
        
        _textView = [[CommentTextView alloc] init];
        @weakify(self);
        [_textView bk_whenTapped:^{
            @strongify(self);
            
        }];
        _textView.delegate = self;
        
        [self loadData:_pageIndex pageSize:_pageSize];
        
    }
    return self;
}


-(void)onSendText:(NSString *)text
{
    [self onSendText:text comment:_isReplay ? self.replayComment : nil ];
}

-(void)dissMissTextView
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.isReplay = NO;
    });
    
}

// comment textView delegate
-(void)onSendText:(NSString *)text comment:(MHComment *) fromComment {
    __weak __typeof(self) wself = self;
    
    MHComment *comment = [[MHComment alloc] init];
    comment.text = text;
    /// 搞个随机字符串
    comment.idstr = [NSString stringWithFormat:@"%ld",[NSObject mh_randomNumberWithFrom:10000000 to:99999999]];
    comment.momentIdstr = @"";
    comment.isReply = (fromComment != nil);
    comment.createdAt = [NSDate date];
    @weakify(self);
    [[[[MHHTTPService sharedInstance] publishCommentWithRecentId:_aweme.recentId content:comment.text parentId:comment.isReply? fromComment.autoId : 0 ] mh_parsedResults] subscribeNext:^(MHComment *comentResponse) {
        @strongify(self);
        [UIView setAnimationsEnabled:NO];
        [self.tableView beginUpdates];
        [self.data insertObject:comentResponse atIndex:0];
        [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        [self.tableView endUpdates];
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
        [UIView setAnimationsEnabled:YES];
        if (self.commentSuccessBlock) {
            self.commentSuccessBlock();
        }
        [UIWindow showTips:@"评论成功"];
    } error:^(NSError *error) {
        [UIWindow showTips:@"评论失败"];
    }];
    
//    comment.fromUser = self.services.client.currentUser;
//    if (itemViewModel.toUser) {
//        comment.isReply = YES;
//        comment.parentId = itemViewModel.parentId;
//    }
//
//    comment.toUser = itemViewModel.toUser;
    
    //    PostCommentRequest *request = [PostCommentRequest new];
    //    request.aweme_id = _awemeId;
    //    request.udid = UDID;
    //    request.text = text;
    //    __block NSURLSessionDataTask *task = [NetworkHelper postWithUrlPath:POST_COMMENT_URL request:request success:^(id data) {
    //        CommentResponse *response = [[CommentResponse alloc] initWithDictionary:data error:nil];
    //        Comment *comment = response.data;
    //        for(NSInteger i = wself.data.count-1; i>=0; i--) {
    //            if(wself.data[i].taskId == task.taskIdentifier) {
    //                wself.data[i] = comment;
    //                break;
    //            }
    //        }
    //        [UIWindow showTips:@"评论成功"];
    //    } failure:^(NSError *error) {
    //        [UIWindow showTips:@"评论失败"];
    //    }];
    //
    //    Comment *comment = [[Comment alloc] init:_awemeId text:text taskId:task.taskIdentifier];
    //    comment.user_type = @"visitor";
    //    comment.visitor = _vistor;
    //
    //    [UIView setAnimationsEnabled:NO];
    //    [_tableView beginUpdates];
    //    [_data insertObject:comment atIndex:0];
    //    [_tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    //    [_tableView endUpdates];
    //    [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
    //    [UIView setAnimationsEnabled:YES];
}

// tableView delegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _data.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [CommentListCell cellHeight:_data[indexPath.row]];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CommentListCell *cell = [tableView dequeueReusableCellWithIdentifier:COMMENT_CELL];
    [cell initData:_data[indexPath.row]];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    MHComment *comment = _data[indexPath.row];
    if (comment.fromUser.userId ==  [MHHTTPService sharedInstance].currentUser.userId)
    {
        MenuPopView *menu = [[MenuPopView alloc] initWithTitles:@[@"删除"]];
        __weak __typeof(self) wself = self;
        menu.onAction = ^(NSInteger index) {
            [wself deleteComment:comment];
        };
        [menu show];
    }else
    {
        self.replayComment = comment;
        self.isReplay = YES;
        [_textView.textView becomeFirstResponder];
        _textView.placeholderLabel.text  = [NSString stringWithFormat:@"回复:%@",comment.commentUserName];
    }
}

//delete comment
- (void)deleteComment:(MHComment *)comment {
    __weak __typeof(self) wself = self;
    [[[MHHTTPService sharedInstance] deleteCommentWith:comment.autoId] subscribeNext:^(id x) {
        NSInteger index = [wself.data indexOfObject:comment];
        [wself.tableView beginUpdates];
        [wself.data removeObjectAtIndex:index];
        [wself.tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:UITableViewRowAnimationRight];
        [wself.tableView endUpdates];
        [UIWindow showTips:@"评论删除成功"];
    } error:^(NSError *error) {
        [UIWindow showTips:@"评论删除失败"];
    }];
    //    DeleteCommentRequest *request = [DeleteCommentRequest new];
    //    request.cid = comment.cid;
    //    request.udid = UDID;
    //    [NetworkHelper deleteWithUrlPath:DELETE_COMMENT_BY_ID_URL request:request success:^(id data) {
    //        NSInteger index = [wself.data indexOfObject:comment];
    //        [wself.tableView beginUpdates];
    //        [wself.data removeObjectAtIndex:index];
    //        [wself.tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:UITableViewRowAnimationRight];
    //        [wself.tableView endUpdates];
    //        [UIWindow showTips:@"评论删除成功"];
    //    } failure:^(NSError *error) {
    //        [UIWindow showTips:@"评论删除失败"];
    //    }];
}

//guesture
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([NSStringFromClass([touch.view.superview class]) isEqualToString:@"CommentListCell"]) {
        return NO;
    }else {
        return YES;
    }
}

- (void)handleGuesture:(UITapGestureRecognizer *)sender {
    CGPoint point = [sender locationInView:_container];
    if(![_container.layer containsPoint:point]) {
        [self dismiss];
        return;
    }
    point = [sender locationInView:_close];
    if([_close.layer containsPoint:point]) {
        [self dismiss];
    }
}

//update method
- (void)show {
    UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
    [window addSubview:self];
    [UIView animateWithDuration:0.15f
                          delay:0.0f
                        options:UIViewAnimationOptionCurveEaseOut
                     animations:^{
                         CGRect frame = self.container.frame;
                         frame.origin.y = frame.origin.y - frame.size.height;
                         self.container.frame = frame;
                     }
                     completion:^(BOOL finished) {
                     }];
    [self.textView show];
}

- (void)dismiss {
    [UIView animateWithDuration:0.15f
                          delay:0.0f
                        options:UIViewAnimationOptionCurveEaseIn
                     animations:^{
                         CGRect frame = self.container.frame;
                         frame.origin.y = frame.origin.y + frame.size.height;
                         self.container.frame = frame;
                     }
                     completion:^(BOOL finished) {
                         [self removeFromSuperview];
                         [self.textView dismiss];
                     }];
}

//load data
- (void)loadData:(NSInteger)pageIndex pageSize:(NSInteger)pageSize {
    __weak __typeof(self) wself = self;
    @weakify(self);

    
    [[[MHHTTPService sharedInstance] getCommentPagedListWithRecentId:_aweme.recentId  pageNum:(int)self.pageIndex  pageSize:pageSize] subscribeNext:^(NSArray *array) {
        @strongify(self);
        self.pageIndex++;
        [UIView setAnimationsEnabled:NO];
        [self.tableView beginUpdates];
        [self.data addObjectsFromArray:array];
        NSMutableArray<NSIndexPath *> *indexPaths = [NSMutableArray array];
        for(NSInteger row = wself.data.count - array.count; row<wself.data.count; row++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
            [indexPaths addObject:indexPath];
        }
        [self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
        [self.tableView endUpdates];
        [UIView setAnimationsEnabled:YES];
        
        [self.loadMore endLoading];
        
        if(array.count % pageSize != 0 ||  array.count == 0 ) {
            [wself.loadMore loadingAll];
        }
//        wself.label.text = [NSString stringWithFormat:@"%ld条评论",(long)response.total_count];
    } error:^(NSError *error) {
        [self.loadMore loadingFailed];
    }];
    

}

//UIScrollViewDelegate Delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat offsetY = scrollView.contentOffset.y;
    if(offsetY < 0) {
        self.frame = CGRectMake(0, -offsetY, self.frame.size.width, self.frame.size.height);
    }
    if (scrollView.isDragging && offsetY < -50) {
        [self dismiss];
    }
}
@end


#pragma comment tableview cell

#define MAX_CONTENT_WIDTH SCREEN_WIDTH - 55 - 35
//cell
@implementation CommentListCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if(self) {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        self.backgroundColor = ColorClear;
        self.clipsToBounds = YES;
//        _avatar = [[UIImageView alloc] init];
//        _avatar.image = [UIImage imageNamed:@"img_find_default"];
//        _avatar.clipsToBounds = YES;
//        _avatar.layer.cornerRadius = 14;
//        [self addSubview:_avatar];
        
//        _likeIcon = [[UIImageView alloc] init];
//        _likeIcon.contentMode = UIViewContentModeCenter;
//        _likeIcon.image = [UIImage imageNamed:@"icCommentLikeBefore_black"];
//        [self addSubview:_likeIcon];
        
//        _nickName = [[UILabel alloc] init];
//        _nickName.numberOfLines = 1;
//        _nickName.textColor = ColorWhiteAlpha60;
//        _nickName.font = SmallFont;
//        [self addSubview:_nickName];
        
//        _content = [[UILabel alloc] init];
//        _content.numberOfLines = 0;
//        _content.textColor = ColorWhiteAlpha80;
//        _content.font = MediumFont;

        [self addSubview:self.content];
        
        _date = [[UILabel alloc] init];
        _date.numberOfLines = 1;
        _date.textColor = ColorGray;
        _date.font = SmallFont;
        [self addSubview:_date];
        
        _likeNum = [[UILabel alloc] init];
        _likeNum.numberOfLines = 1;
        _likeNum.textColor = ColorGray;
        _likeNum.font = SmallFont;
        [self addSubview:_likeNum];
        
        _splitLine = [[UIView alloc] init];
        _splitLine.backgroundColor = ColorWhiteAlpha10;
        [self addSubview:_splitLine];
        
    }
    return self;
}

-(YYLabel *)content
{
    if (!_content) {
        _content = [[YYLabel alloc] init];
        _content.backgroundColor = self.contentView.backgroundColor;
        /// 垂直方向中心对齐
        _content.textVerticalAlignment = YYTextVerticalAlignmentCenter;
        /// 异步渲染和布局
        _content.displaysAsynchronously = NO;
        /// 利用textLayout来设置text、font、textColor...
        _content.ignoreCommonProperties = YES;
        _content.fadeOnAsynchronouslyDisplay = NO;
        _content.fadeOnHighlight = NO;
        _content.preferredMaxLayoutWidth = MAX_CONTENT_WIDTH;
        
    }
    return _content;
}

-(void)layoutSubviews {
    [super layoutSubviews];
//    [_avatar mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.left.equalTo(self).inset(15);
//        make.width.height.mas_equalTo(28);
//    }];
//    [_likeIcon mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.right.equalTo(self).inset(15);
//        make.width.height.mas_equalTo(20);
//    }];
//    [_nickName mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self).offset(10);
//        make.left.equalTo(self.avatar.mas_right).offset(10);
//        make.right.equalTo(self.likeIcon.mas_left).inset(25);
//    }];
    [_content mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self).offset(10);
        make.top.left.equalTo(self).inset(15);
        make.width.mas_lessThanOrEqualTo(MAX_CONTENT_WIDTH);
//        make.height.mas_equalTo(self.contentLayout.textBoundingSize.height);
    }];
//    [_date mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.content.mas_bottom).offset(5);
//        make.left.right.equalTo(self.nickName);
//    }];
//    [_likeNum mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerX.equalTo(self.likeIcon);
//        make.top.equalTo(self.likeIcon.mas_bottom).offset(5);
//    }];
    [_splitLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.content);
        make.right.equalTo(self);
        make.bottom.equalTo(self);
        make.height.mas_equalTo(0.5);
    }];
}

-(void)initData:(MHComment *)comment {
    NSURL *avatarUrl;
    avatarUrl = [NSURL URLWithString:comment.allCommentUserHeadPic];
    _nickName.text = [NSString stringWithFormat:@"%@:",comment.commentUserName];
    //    if([@"user" isEqualToString:comment.user_type]) {
    //
    //    }else {
    //        avatarUrl = [NSURL URLWithString:comment.visitor.avatar_thumbnail.url];
    //        _nickName.text = [comment.visitor formatUDID];
    //    }
    
    
    NSMutableAttributedString *contentAttr = [[NSMutableAttributedString alloc] init];
    
    /// : 正文富文本 （还需要匹配超链接 表情 电话号码 @xx）
    NSMutableAttributedString *textAttr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"：%@",comment.text]];
    textAttr.yy_color = MHMainTextColor;
    textAttr.yy_font = MHRegularFont_15;
    
    /// 点击的高亮的
    YYTextBorder *border = [YYTextBorder new];
    border.cornerRadius = 0;
    border.insets = UIEdgeInsetsMake(0, -1, 0, -1);
    border.fillColor = MHMomentTextHighlightBackgroundColor;
    
    /// XXX （来源）
    NSMutableAttributedString *fromAttr = [[NSMutableAttributedString alloc] initWithString:comment.commentUserName];
    fromAttr.yy_color = MHLinkTextColor;
    fromAttr.yy_font = MHRegularFont_15;
    /// 点击高亮
    YYTextHighlight *fromHighlight = [YYTextHighlight new];

    // 将用户数据带出去
    //        se
    //        fromHighlight.userInfo = @{MHMomentUserInfoKey:comment.fromUser?? };
    [fromHighlight setBackgroundBorder:border];
    [fromAttr yy_setTextHighlight:fromHighlight range:fromAttr.yy_rangeOfAll];
    
    
//    self.content.
    
    
    
    /// 是否有 回复xxx
    if (comment.replyUserName.length > 0) {
        /// 回复
        NSMutableAttributedString *replyAttr = [[NSMutableAttributedString alloc] initWithString:@"回复"];
        replyAttr.yy_color = textAttr.yy_color;
        replyAttr.yy_font = textAttr.yy_font;
        
        /// xxx（目标）
        NSMutableAttributedString *toAttr = [[NSMutableAttributedString alloc] initWithString:comment.replyUserName];
        toAttr.yy_color = fromAttr.yy_color;
        toAttr.yy_font = fromAttr.yy_font;
        /// 高亮
        YYTextHighlight *toHighlight = [[YYTextHighlight alloc] init];
        [toHighlight setBackgroundBorder:border];
        /// 将用户数据带出去
//        toHighlight.userInfo = @{MHMomentUserInfoKey:comment.toUser};
        [toAttr yy_setTextHighlight:toHighlight range:toAttr.yy_rangeOfAll];
        
        /// 拼接数据 (A回复B)
        [replyAttr appendAttributedString:toAttr];
        [fromAttr appendAttributedString:replyAttr];
    }
    
    /// 拼接 （A回复B：xxxx   或者  A：xxxx）
    [contentAttr appendAttributedString:fromAttr];
    [contentAttr appendAttributedString:textAttr];
    
    /// 统一配置
    contentAttr.yy_lineBreakMode = NSLineBreakByCharWrapping;
    contentAttr.yy_alignment = NSTextAlignmentLeft;
    [contentAttr mh_regexContentWithWithEmojiImageFontSize:15];
    YYTextContainer *nameLableContainer = [YYTextContainer containerWithSize:CGSizeMake(MAX_CONTENT_WIDTH-1, MAXFLOAT)];
    nameLableContainer.maximumNumberOfRows = 0;
    YYTextLayout *nameLableLayout = [YYTextLayout layoutWithContainer:nameLableContainer text:contentAttr.copy];
    self.contentLayout = nameLableLayout;
    self.content.textLayout = nameLableLayout;
    /// 匹配正则 表情+电话+url...
   
    
//        [_content mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.top.equalTo(self.nickName.mas_bottom).offset(5);
//            make.left.equalTo(self.nickName);
//            make.width.mas_lessThanOrEqualTo(nameLableLayout.textBoundingSize.width);
//        }];

    
//    self.content.frame =   CGRectMake(self.nickName.x , CGRectGetMaxY(self.nickName.frame) + 5, nameLableLayout.textBoundingSize.width, nameLableLayout.textBoundingSize.height);
    
//    self.avatar.image = [UIImage imageNamed:@"icon_mine_default"];
        __weak __typeof(self) wself = self;
    [self.avatar yy_setImageWithURL:avatarUrl placeholder:MHDefaultAvatar(MHDefaultAvatarTypeDefualt) options:nil completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error) {
        image = [image drawCircleImage];
        wself.avatar.image = image;
    }];
  
    _date.text = [MHMomentHelper createdAtTimeWithSourceDate:comment.createdAt];
//    _likeNum.text = [NSString formatCount:comment.digg_count];
    
}

+(CGFloat)cellHeight:(MHComment *)comment {
    NSMutableAttributedString *contentAttr = [[NSMutableAttributedString alloc] init];
    
    /// : 正文富文本 （还需要匹配超链接 表情 电话号码 @xx）
    NSMutableAttributedString *textAttr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"：%@",comment.text]];
    textAttr.yy_color = MHMainTextColor;
    textAttr.yy_font = MHRegularFont_15;
    
    /// 点击的高亮的
    YYTextBorder *border = [YYTextBorder new];
    border.cornerRadius = 0;
    border.insets = UIEdgeInsetsMake(0, -1, 0, -1);
    border.fillColor = MHMomentTextHighlightBackgroundColor;
    
    /// XXX （来源）
    NSMutableAttributedString *fromAttr = [[NSMutableAttributedString alloc] initWithString:comment.commentUserName];
    fromAttr.yy_color = MHLinkTextColor;
    fromAttr.yy_font = MHRegularFont_15;
    /// 点击高亮
    YYTextHighlight *fromHighlight = [YYTextHighlight new];
    
    // 将用户数据带出去
    //        se
    //        fromHighlight.userInfo = @{MHMomentUserInfoKey:comment.fromUser?? };
    [fromHighlight setBackgroundBorder:border];
    [fromAttr yy_setTextHighlight:fromHighlight range:fromAttr.yy_rangeOfAll];
    
    
    //    self.content.
    
    
    
    /// 是否有 回复xxx
    if (comment.replyUserName.length > 0) {
        /// 回复
        NSMutableAttributedString *replyAttr = [[NSMutableAttributedString alloc] initWithString:@"回复"];
        replyAttr.yy_color = textAttr.yy_color;
        replyAttr.yy_font = textAttr.yy_font;
        
        /// xxx（目标）
        NSMutableAttributedString *toAttr = [[NSMutableAttributedString alloc] initWithString:comment.replyUserName];
        toAttr.yy_color = fromAttr.yy_color;
        toAttr.yy_font = fromAttr.yy_font;
        /// 高亮
        YYTextHighlight *toHighlight = [[YYTextHighlight alloc] init];
        [toHighlight setBackgroundBorder:border];
        /// 将用户数据带出去
        //        toHighlight.userInfo = @{MHMomentUserInfoKey:comment.toUser};
        [toAttr yy_setTextHighlight:toHighlight range:toAttr.yy_rangeOfAll];
        
        /// 拼接数据 (A回复B)
        [replyAttr appendAttributedString:toAttr];
        [fromAttr appendAttributedString:replyAttr];
    }
    
    /// 拼接 （A回复B：xxxx   或者  A：xxxx）
    [contentAttr appendAttributedString:fromAttr];
    [contentAttr appendAttributedString:textAttr];
    
    /// 统一配置
    contentAttr.yy_lineBreakMode = NSLineBreakByCharWrapping;
    contentAttr.yy_alignment = NSTextAlignmentLeft;
    [contentAttr mh_regexContentWithWithEmojiImageFontSize:15];
    YYTextContainer *nameLableContainer = [YYTextContainer containerWithSize:CGSizeMake(MAX_CONTENT_WIDTH, MAXFLOAT)];
    nameLableContainer.maximumNumberOfRows = 0;
    YYTextLayout *nameLableLayout = [YYTextLayout layoutWithContainer:nameLableContainer text:contentAttr.copy];
    return nameLableLayout.textBoundingSize.height + 20 ;
}
@end







#pragma TextView

#define LEFT_INSET                 15
#define RIGHT_INSET                60
#define TOP_BOTTOM_INSET           15

//#define LEFT_INSET 16
//#define RIGHT_INSET 50
//#define TOP_BOTTOM_INSET 15
@interface CommentTextView ()<UITextViewDelegate, UIGestureRecognizerDelegate>
@property (nonatomic, assign) CGFloat            textHeight;
@property (nonatomic, assign) CGFloat            keyboardHeight;
//@property (nonatomic, strong ) UILabel            *placeholderLabel;
@property (nonatomic, strong) UIImageView        *atImageView;
@property (nonatomic, strong) UIVisualEffectView *visualEffectView;
@end

@implementation CommentTextView
- (instancetype)init {
    self = [super init];
    if(self) {
        self.frame = SCREEN_FRAME;
        self.backgroundColor = ColorClear;
        [self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleGuesture:)]];
        
        _textView = [[UITextView alloc] init];
        _textView.backgroundColor = MHTextColorF6F6F6;
        
        _textView.clipsToBounds = NO;
        _textView.textColor = ColorWhite;
        _textView.font = BigFont;
        _textView.returnKeyType = UIReturnKeySend;
        _textView.scrollEnabled = NO;
        _textView.textContainer.lineBreakMode = NSLineBreakByTruncatingTail;
        _textView.textContainerInset = UIEdgeInsetsMake(TOP_BOTTOM_INSET, LEFT_INSET, TOP_BOTTOM_INSET, RIGHT_INSET);
        _textView.textContainer.lineFragmentPadding = 0;
        _textHeight = ceilf(_textView.font.lineHeight);
        
        _placeholderLabel = [[UILabel alloc]init];
        _placeholderLabel.text = @"说点什么吧~";
        _placeholderLabel.textColor = ColorGray;
        _placeholderLabel.font = BigFont;
        _placeholderLabel.frame = CGRectMake(LEFT_INSET, 0, SCREEN_WIDTH - LEFT_INSET - RIGHT_INSET, 50);
        [_textView addSubview:_placeholderLabel];
        
        _atImageView = [[UIImageView alloc] init];
        _atImageView.contentMode = UIViewContentModeCenter;
        _atImageView.image = [UIImage imageNamed:@"iconWhiteaBefore"];
//        [_textView addSubview:_atImageView];
        [self addSubview:_textView];
        
        
        _textView.delegate = self;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [self updateViewFrame];
}

- (void)updateViewFrame {
    [self updateTextViewFrame];
    
    _atImageView.frame = CGRectMake(SCREEN_WIDTH - 50, 0, 50, 50);
    
    UIBezierPath* rounded = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(10.0f, 10.0f)];
    CAShapeLayer* shape = [[CAShapeLayer alloc] init];
    [shape setPath:rounded.CGPath];
    _textView.layer.mask = shape;
    
}

- (void)updateTextViewFrame {
    CGFloat textViewHeight = _keyboardHeight > 0 ? _textHeight + 2*TOP_BOTTOM_INSET : ceilf(_textView.font.lineHeight) + 2*TOP_BOTTOM_INSET;
    _textView.frame = CGRectMake(0, SCREEN_HEIGHT - _keyboardHeight - textViewHeight, SCREEN_WIDTH, textViewHeight);
}

//keyboard notification
- (void)keyboardWillShow:(NSNotification *)notification {
    _keyboardHeight = [notification keyBoardHeight];
    [self updateTextViewFrame];
    _atImageView.image = [UIImage imageNamed:@"iconWhiteaBefore"];
    _textView.backgroundColor = ColorWhite;
    _textView.textColor = ColorBlack;
    self.backgroundColor = ColorBlackAlpha60;
}

- (void)keyboardWillHide:(NSNotification *)notification {
    _keyboardHeight = 0;
    [self updateTextViewFrame];
    _atImageView.image = [UIImage imageNamed:@"iconWhiteaBefore"];
    _textView.backgroundColor = MHTextColorF6F6F6;
    _textView.textColor = ColorWhite;
    _placeholderLabel.text = @"说点什么吧~";
    _placeholderLabel.hidden = false;
    self.backgroundColor = ColorClear;
}

//textView delegate
-(void)textViewDidChange:(UITextView *)textView {
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithAttributedString:textView.attributedText];
    
    if(!textView.hasText) {
        [_placeholderLabel setHidden:NO];
        _textHeight = ceilf(_textView.font.lineHeight);
    }else {
        [_placeholderLabel setHidden:YES];
        _textHeight = [attributedText multiLineSize:SCREEN_WIDTH - LEFT_INSET - RIGHT_INSET].height;
    }
    [self updateTextViewFrame];
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if([text isEqualToString:@"\n"]) {
        if(_delegate) {
            [_delegate onSendText:textView.text];
            textView.text = @"";
            _textHeight = ceilf(textView.font.lineHeight);
            [textView resignFirstResponder];
        }
        return NO;
    }
    return YES;
}

//handle guesture tap
- (void)handleGuesture:(UITapGestureRecognizer *)sender {
    CGPoint point = [sender locationInView:_textView];
    if(![_textView.layer containsPoint:point] && self.textView.isFirstResponder) {
        [_textView resignFirstResponder];
    }
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    UIView *hitView = [super hitTest:point withEvent:event];
    if(hitView == self){
        if(hitView.backgroundColor == ColorClear) {
            return nil;
        }
    }
    return hitView;
}

//update method
- (void)show {
    UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
    [window addSubview:self];
}

- (void)dismiss {
    [self removeFromSuperview];
    if (_delegate) {
        [_delegate dissMissTextView];
    }
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end

